/**
 * param(string) videoDomId video标签的id
 * param(string) canvasDomId canvas标签的id
 * param(Boolean) videoDownload 结束时浏览器是否下载录制的视频
 */ 
 class screenshot{
    constructor(videoDomId,canvasDomId,videoDownload=true){
        
        //获取canvas元素
        this.canvas = document.getElementById(canvasDomId)
        //获取video元素
        this.videoElem = document.getElementById(videoDomId)
        //截取配置
        this.displayMediaOptions = { // 参数的详情可以在mdn网站查找
            video: {
                cursor: "always",
            },
            audio: false,//是否录制音频
        };
        this.mediaRecorder=null//视频流对象
        this.videoDownload = videoDownload//判断结束时浏览器是否下载录制的视频
        this.recordedChunks = [] //储存视频数据
        this.blob = {}
    }
    /**
     * 开始
     */
    async startCapture() {
        try {
            this.videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(this.displayMediaOptions);
            this.videoElem.addEventListener("loadedmetadata", ()=> {
                this.canvas.width = this.videoElem.videoWidth;
                this.canvas.height = this.videoElem.videoHeight;
            });
            var options = { mimeType: "video/webm; codecs=vp9" };
            this.mediaRecorder = new MediaRecorder(this.videoElem.srcObject, options);
            this.mediaRecorder.ondataavailable = this.handleDataAvailable.bind(this);
            this.mediaRecorder.start();
            this.videoElem.play();
        } catch (err) {
            console.error("Error: " + err);
        }
    }
    //储存视频数据
    handleDataAvailable(event) {
        if (event.data.size > 0) {
            this.recordedChunks.push(event.data);
            this.blob = new Blob(this.recordedChunks, {
                type: "video/webm"
            });
            if(this.videoDownload){
                this.download();
            }
        } else {
            console.log('没有得到视频数据')
        }
    }
    /**
     * 视频下载函数
     */
    download() {
        var url = URL.createObjectURL(this.blob);//创建url对象
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = url;
        a.download = "test.webm";
        a.click();
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url);//释放url对象
    }
    /** 
     * param{Boolean} bol 判断是否让浏览器下载图片
     * 下载截图
    */
    downloadImg(bol){
            let ctx = this.canvas.getContext("2d");
            ctx.drawImage(this.videoElem, 0, 0, this.videoElem.videoWidth, this.videoElem.videoHeight);
            //拿到一个dataUrl，可new Image()，然后图片的对象的src设置为url，就可以得到图片dom元素
            let imgURL = this.canvas.toDataURL("image/jpeg");

            if(bol){
                var a = document.createElement('a');          // 创建一个a节点插入的document
                var event = new MouseEvent('click')           // 模拟鼠标click点击事件
                a.download = 'beautifulGirl'                  // 设置a节点的download属性值
                a.href = imgURL;                                 // 将图片的src赋值给a节点的href
                a.dispatchEvent(event) 
            }
            return imgURL
    }
    /**
     * 结束录制
     */
    stopCapture(evt) {
        return new Promise((resolve,reject)=>{
            let tracks = this.videoElem.srcObject.getTracks();
            tracks.forEach(
                track => track.stop()
            );
            this.videoElem.srcObject = null;
            this.mediaRecorder = null
            this.recordedChunks= []
            setTimeout(()=>{
                resolve(this.blob)
            },100)
        })
    }
}
export default screenshot